/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.mockexam.theory.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.jeesite.modules.zx.audio.bank.entity.TaudioBank;
import com.jeesite.modules.zx.audio.bank.service.TaudioBankService;
import com.jeesite.modules.zx.picture.bank.entity.TpictureBank;
import com.jeesite.modules.zx.picture.bank.service.TpictureBankService;
import com.jeesite.modules.zx.problem.bank.entity.TproblemBank;
import com.jeesite.modules.zx.problem.bank.service.TproblemBankService;
import com.jeesite.modules.zx.reading.bank.entity.TreadingBank;
import com.jeesite.modules.zx.reading.bank.service.TreadingBankService;
import com.jeesite.modules.zx.subject.bank.entity.TsubjectBank;
import com.jeesite.modules.zx.subject.bank.service.TsubjectBankService;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.zx.mockexam.theory.entity.TmockexamTheory;
import com.jeesite.modules.zx.mockexam.theory.service.TmockexamTheoryService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;

/**
 * 理论模拟考试对象表Controller
 * @author zpp
 * @version 2020-02-09
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/mockexam/theory/tmockexamTheory")
public class TmockexamTheoryController extends BaseController {

	@Autowired
	private TmockexamTheoryService tmockexamTheoryService;
	@Autowired
	private PostService postService;
	@Autowired
	private TquestionBankService tquestionBankService;

	@Autowired
	private TpictureBankService tpictureBankService;
	@Autowired
	private TreadingBankService treadingBankService;
	@Autowired
	private TaudioBankService taudioBankService;
    @Autowired
	private TproblemBankService tproblemBankService;
    @Autowired
    private TsubjectBankService tsubjectBankService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TmockexamTheory get(String id, boolean isNewRecord) {
		return tmockexamTheoryService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:view")
	@RequestMapping(value = {"list", ""})
	public String list(TmockexamTheory tmockexamTheory, Model model) {
		model.addAttribute("tmockexamTheory", tmockexamTheory);
		return "modules/zx/mockexam/theory/tmockexamTheoryList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<TmockexamTheory> listData(TmockexamTheory tmockexamTheory) {
		if (StringUtils.isBlank(tmockexamTheory.getParentCode())) {
			tmockexamTheory.setParentCode(TmockexamTheory.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(tmockexamTheory.getObjName())){
			tmockexamTheory.setParentCode(null);
		}
		if (tmockexamTheory.getObjType() != null){
			tmockexamTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamTheory.getRemarks())){
			tmockexamTheory.setParentCode(null);
		}
		if (tmockexamTheory.getObjExplain() != null){
			tmockexamTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamTheory.getObjAnswer())){
			tmockexamTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamTheory.getIntroduction())){
			tmockexamTheory.setParentCode(null);
		}
		List<TmockexamTheory> list = tmockexamTheoryService.findList(tmockexamTheory);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:view")
	@RequestMapping(value = "form")
	public String form(TmockexamTheory tmockexamTheory, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tmockexamTheory = createNextNode(tmockexamTheory);
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tmockexamTheory", tmockexamTheory);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)&&objExplain.equals("3")){
			TquestionBank quetionBank=new TquestionBank();
			quetionBank.setObjType(tmockexamTheory.getObjType());
			//查询单选
			List<TquestionBank> findList = tquestionBankService.findList(quetionBank);
			model.addAttribute("questionList",findList);
		}
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/theory/tmockexamTheoryForm"+objExplain;
		}
		return "modules/zx/mockexam/theory/tmockexamTheoryForm";
	}
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:view")
	@RequestMapping(value = "questionForm")
	public String questionForm(TmockexamTheory tmockexamTheory, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tmockexamTheory = createNextNode(tmockexamTheory);
		String postCode=tmockexamTheory.getPost();
		
		Integer objType = tmockexamTheory.getObjType();
		TquestionBank question=new TquestionBank();
		question.setObjType(objType);
        if(StringUtils.isNotBlank(postCode)){
        	question.setPost(postCode);
		}else{
			question.getSqlMap().getWhere().and("post",QueryType.IS_NULL, null);
		}
		List<TquestionBank> findList = tquestionBankService.findList(question);
		Post post = new Post();
		model.addAttribute("questionList", findList);
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tmockexamTheory", tmockexamTheory);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/theory/tmockexamTheoryForm"+objExplain;
		}
		return "modules/zx/mockexam/theory/tmockexamTheoryForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public TmockexamTheory createNextNode(TmockexamTheory tmockexamTheory) {
		if (StringUtils.isNotBlank(tmockexamTheory.getParentCode())){
			tmockexamTheory.setParent(tmockexamTheoryService.get(tmockexamTheory.getParentCode()));
		}
		if (tmockexamTheory.getIsNewRecord()) {
			TmockexamTheory where = new TmockexamTheory();
			where.setParentCode(tmockexamTheory.getParentCode());
			where.getSqlMap().getWhere().or("status",QueryType.IN, Lists.newArrayList("0","1"));
			TmockexamTheory last = tmockexamTheoryService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				tmockexamTheory.setTreeSort(last.getTreeSort() + 30);
				tmockexamTheory.setId(IdGen.nextCode(last.getId()));
			}else if (tmockexamTheory.getParent() != null){
				tmockexamTheory.setId(tmockexamTheory.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (tmockexamTheory.getTreeSort() == null){
			tmockexamTheory.setTreeSort(TmockexamTheory.DEFAULT_TREE_SORT);
		}
		return tmockexamTheory;
	}

	/**
	 * 保存理论模拟考试对象表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TmockexamTheory tmockexamTheory) {
		tmockexamTheoryService.save(tmockexamTheory);
		return renderResult(Global.TRUE, text("保存理论模拟考试对象表成功！"));
	}

	/**
	 * 保存理论模拟考试对象表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@PostMapping(value = "save2")
	@ResponseBody
	public String save2(@Validated TmockexamTheory tmockexamTheory) {
		tmockexamTheoryService.save(tmockexamTheory);
		String id = tmockexamTheory.getId();
		Integer num = null;
		List<String> bankIds = new ArrayList<>();
		List<TproblemBank> tproblemBankList = null;
		List<TquestionBank> quetbankList = null;
		Integer objType = tmockexamTheory.getObjType();
		String post = "-1".equals(tmockexamTheory.getPost())?null:tmockexamTheory.getPost();
		//删除
		TmockexamTheory theory = new TmockexamTheory();
		theory.setParentCode(id);
		List<TmockexamTheory> deleteList = tmockexamTheoryService.findList(theory);
		if (deleteList!=null && deleteList.size()>0){
			deleteList.forEach(item->{
				tmockexamTheoryService.delete(item);
			});
		}
		if (objType!=null){
			switch (objType){
				case 3 : //阅读理解
					num = tmockexamTheory.getNumBars() == null?1:tmockexamTheory.getNumBars();
					TreadingBank reading = new TreadingBank();
					reading.getSqlMap().getWhere().and("post",QueryType.EQ,post);
					reading.getSqlMap().getOrder().setOrderBy("RAND() LIMIT "+num);
					List<TreadingBank> treadingBankList = treadingBankService.findList(reading);
					bankIds = treadingBankList.stream().map(TreadingBank::getId).collect(Collectors.toList());
					tproblemBankList = getProblemBankList(bankIds);
					break;
				case 4 : //图片题
					num = tmockexamTheory.getNumBars() == null?1:tmockexamTheory.getNumBars();
					TpictureBank picture = new TpictureBank();
					picture.getSqlMap().getWhere().and("post",QueryType.EQ,post);
					picture.getSqlMap().getOrder().setOrderBy("RAND() LIMIT "+num);
					List<TpictureBank> tpictureBankList = tpictureBankService.findList(picture);
					bankIds = tpictureBankList.stream().map(TpictureBank::getId).collect(Collectors.toList());
					tproblemBankList = getProblemBankList(bankIds);
					break;
				case 5 ://音频题
					num = tmockexamTheory.getNumBars() == null?1:tmockexamTheory.getNumBars();
					TaudioBank audio = new TaudioBank();
					audio.getSqlMap().getWhere().and("post",QueryType.EQ,post);
					audio.getSqlMap().getOrder().setOrderBy("RAND() LIMIT "+num);
					List<TaudioBank> taudioBankList = taudioBankService.findList(audio);
					bankIds = taudioBankList.stream().map(TaudioBank::getId).collect(Collectors.toList());
					tproblemBankList = getProblemBankList(bankIds);
					break;
				default :
					num = tmockexamTheory.getNumBars() == null?30:tmockexamTheory.getNumBars();
					TquestionBank quebank=new TquestionBank();
//					quebank.getSqlMap().getWhere().and("obj_type",QueryType.EQ,objType).or("post",QueryType.EQ,post);
					quebank.setObjType(objType);
					quebank.setPost(post);
					quebank.getSqlMap().getOrder().setOrderBy("RAND() LIMIT "+ num);
					quetbankList = tquestionBankService.findList(quebank);
					break;
			}
		}
		int numBars = 0;
		final BigDecimal[] totalScore = {new BigDecimal(0)};
		if (quetbankList!=null && quetbankList.size()>0){
			numBars = quetbankList.size();
			quetbankList.forEach(tquestionBank->{
				totalScore[0] = totalScore[0].add(new BigDecimal(tquestionBank.getScore()));
				TmockexamTheory examTheory = new TmockexamTheory();
				examTheory.setParentCode(id);
				examTheory = createNextNode(examTheory);
				examTheory.setObjName(tquestionBank.getId());
				examTheory.setObjType(objType);
				examTheory.setPost(post);
				examTheory.setScore(new BigDecimal(tquestionBank.getScore()));
				examTheory.setObjExplain(tmockexamTheory.getObjExplain()+1);
				tmockexamTheoryService.save(examTheory);
			});
		} else if (tproblemBankList!=null && tproblemBankList.size()>0){
			numBars = tproblemBankList.size();
			tproblemBankList.forEach(tproblemBank->{
				totalScore[0] = totalScore[0].add(new BigDecimal(tproblemBank.getScore()));
				TmockexamTheory examTheory = new TmockexamTheory();
				examTheory.setParentCode(id);
				examTheory = createNextNode(examTheory);
				examTheory.setObjName(tproblemBank.getId());
				examTheory.setObjType(objType);
				examTheory.setPost(post);
				examTheory.setScore(new BigDecimal(tproblemBank.getScore()));
				examTheory.setObjExplain(tmockexamTheory.getObjExplain()+1);
				tmockexamTheoryService.save(examTheory);
			});
		}
		tmockexamTheory.setScore(totalScore[0]);
		tmockexamTheory.setNumBars(numBars);
		tmockexamTheory.setTreeLeaf(numBars==0?"1":"0");
		tmockexamTheoryService.update(tmockexamTheory);
		return renderResult(Global.TRUE, text(numBars==0?"没有获取到该岗位的题目请手动增加":"保存理论模拟考试对象表成功！"));
	}

	/**
	 * 根据阅读理解Id，图片题ID，音频题ID 获取问题
	 * @param bankIds
	 * @return
	 */
	private List<TproblemBank>  getProblemBankList(List<String> bankIds){
		if (bankIds.size()>0){
			TsubjectBank subjectWhere = new TsubjectBank();
			subjectWhere.getSqlMap().getWhere().and("parent_id", QueryType.IN, bankIds);
			List<TsubjectBank> subjectBankList = tsubjectBankService.findList(subjectWhere);
			if (subjectBankList.size()>0){
				List<String> subjectIds = subjectBankList.stream().map(TsubjectBank::getId).collect(Collectors.toList());
				TproblemBank problemWhere = new TproblemBank();
				problemWhere.getSqlMap().getWhere().and("subject_id", QueryType.IN, subjectIds);
				return tproblemBankService.findList(problemWhere);
			}
		}
		return null;
	}

	/**
	 * 停用理论模拟考试对象表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TmockexamTheory tmockexamTheory) {
		TmockexamTheory where = new TmockexamTheory();
		where.setStatus(TmockexamTheory.STATUS_NORMAL);
		where.setParentCodes("," + tmockexamTheory.getId() + ",");
		long count = tmockexamTheoryService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该理论模拟考试对象表包含未停用的子理论模拟考试对象表！"));
		}
		tmockexamTheory.setStatus(TmockexamTheory.STATUS_DISABLE);
		tmockexamTheoryService.updateStatus(tmockexamTheory);
		return renderResult(Global.TRUE, text("停用理论模拟考试对象表成功"));
	}
	
	/**
	 * 启用理论模拟考试对象表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TmockexamTheory tmockexamTheory) {
		tmockexamTheory.setStatus(TmockexamTheory.STATUS_NORMAL);
		tmockexamTheoryService.updateStatus(tmockexamTheory);
		return renderResult(Global.TRUE, text("启用理论模拟考试对象表成功"));
	}
	
	/**
	 * 删除理论模拟考试对象表
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TmockexamTheory tmockexamTheory) {
        TmockexamTheory where = new TmockexamTheory();
		where.setParentCodes("," + tmockexamTheory.getId() + ",");
		List<TmockexamTheory> deleteList = tmockexamTheoryService.findList(where);
		if (deleteList!=null && deleteList.size()>0){
			deleteList.forEach(item->{
				tmockexamTheoryService.delete(item);
			});
		}
		tmockexamTheoryService.delete(tmockexamTheory);
		return renderResult(Global.TRUE, text("删除理论模拟考试对象表成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<TmockexamTheory> list = tmockexamTheoryService.findList(new TmockexamTheory());
		for (int i=0; i<list.size(); i++){
			TmockexamTheory e = list.get(i);
			// 过滤非正常的数据
			if (!TmockexamTheory.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getObjName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("zx:mockexam:theory:tmockexamTheory:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(TmockexamTheory tmockexamTheory){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		tmockexamTheoryService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}